package com.securitydemo.securitydemo.controller;

import com.securitydemo.securitydemo.pojo.Admin;
import com.securitydemo.securitydemo.pojo.LoginParam;
import com.securitydemo.securitydemo.pojo.RespBean;
import com.securitydemo.securitydemo.service.IAdminService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;

@RestController
@Api(tags = "登录")
@RequestMapping
public class LoginController {
    @Autowired
    private IAdminService adminService;

    @ApiOperation(value = "登陆之后返回token")
    @PostMapping("/login")
    public RespBean login(@RequestBody LoginParam loginParam, HttpServletRequest request){
        return adminService.login(loginParam.getUsername(),loginParam.getPassword(),loginParam.getCode(),request);
    }

    @ApiOperation(value = "退出登录")
    @PostMapping("/logout")
    public RespBean logout(){
        return RespBean.success("注销成功！");
    }

    /**
     * 因为登陆对象已经设置到security全局当中所以需要 Principal 获取用户信息
     * @param principal
     * @return
     */
    @ApiOperation(value = "获取当前用户信息")
    @GetMapping("/getAdminInfo")
    public Admin getAdminInfo(Principal principal){
        if(null==principal){
            return  null;
        }
        String username = principal.getName();
        Admin admin = adminService.getAdminByUsername(username);
        admin.setPassword(null);
        return admin;
    }


}
